<template>
  <view class="half-hour-picker">
    <picker 
      mode="multiSelector" 
      :value="pickerValue" 
      :range="pickerRange"
      @change="onPickerChange"
      @columnchange="onColumnChange">
      <view class="picker-display">
        <text>{{ displayText || placeholder }}</text>
        <text class="picker-arrow">></text>
      </view>
    </picker>
  </view>
</template>

<script>
export default {
  name: 'HalfHourPicker',
  props: {
    // 当前选中的时间值 (格式: "HH:mm")
    value: {
      type: String,
      default: ''
    },
    // 占位符文本
    placeholder: {
      type: String,
      default: '选择时间'
    },
    // 开始时间 (格式: "HH:mm")
    startTime: {
      type: String,
      default: '00:00'
    },
    // 结束时间 (格式: "HH:mm")
    endTime: {
      type: String,
      default: '23:30'
    }
  },
  
  data() {
    return {
      pickerValue: [0, 0], // [小时索引, 分钟索引]
      pickerRange: [[], []], // [小时数组, 分钟数组]
    }
  },
  
  computed: {
    // 显示文本
    displayText() {
      if (!this.value) return ''
      return this.value
    }
  },
  
  watch: {
    value: {
      handler(newVal) {
        this.initPickerValue(newVal)
      },
      immediate: true
    },
    startTime() {
      this.initPickerRange()
    },
    endTime() {
      this.initPickerRange()
    }
  },
  
  mounted() {
    this.initPickerRange()
  },
  
  methods: {
    // 初始化选择器范围
    initPickerRange() {
      const hours = []
      const minutes = ['00', '30'] // 固定为整点和半点
      
      // 解析开始和结束时间
      const [startHour, startMinute] = this.startTime.split(':').map(Number)
      const [endHour, endMinute] = this.endTime.split(':').map(Number)
      
      // 生成小时范围
      for (let h = startHour; h <= endHour; h++) {
        const hourStr = h.toString().padStart(2, '0')
        hours.push(hourStr)
      }
      
      this.pickerRange = [hours, minutes]
      
      // 重新初始化选中值
      this.initPickerValue(this.value)
    },
    
    // 初始化选中值
    initPickerValue(timeStr) {
      if (!timeStr || this.pickerRange[0].length === 0) {
        this.pickerValue = [0, 0]
        return
      }
      
      const [hour, minute] = timeStr.split(':')
      const hourIndex = this.pickerRange[0].findIndex(h => h === hour)
      const minuteIndex = this.pickerRange[1].findIndex(m => m === minute)
      
      this.pickerValue = [
        hourIndex >= 0 ? hourIndex : 0,
        minuteIndex >= 0 ? minuteIndex : 0
      ]
    },
    
    // 选择器值改变
    onPickerChange(e) {
      const [hourIndex, minuteIndex] = e.detail.value
      this.pickerValue = [hourIndex, minuteIndex]

      const hour = this.pickerRange[0][hourIndex]
      const minute = this.pickerRange[1][minuteIndex]
      const timeStr = `${hour}:${minute}`

      // 验证选择的时间是否在有效范围内
      if (this.isValidTime(timeStr)) {
        this.$emit('change', timeStr)
      }
    },

    // 验证时间是否有效
    isValidTime(timeStr) {
      const [hour, minute] = timeStr.split(':').map(Number)
      const [startHour, startMinute] = this.startTime.split(':').map(Number)
      const [endHour, endMinute] = this.endTime.split(':').map(Number)

      const timeMinutes = hour * 60 + minute
      const startMinutes = startHour * 60 + startMinute
      const endMinutes = endHour * 60 + endMinute

      return timeMinutes >= startMinutes && timeMinutes <= endMinutes
    },
    
    // 列改变事件
    onColumnChange(e) {
      const { column, value } = e.detail

      // 如果改变的是小时列，需要检查分钟的有效性
      if (column === 0) {
        const selectedHour = parseInt(this.pickerRange[0][value])
        const [startHour, startMinute] = this.startTime.split(':').map(Number)
        const [endHour, endMinute] = this.endTime.split(':').map(Number)

        let availableMinutes = ['00', '30']

        // 如果选择的是开始小时，且开始分钟不是00，则分钟选项需要调整
        if (selectedHour === startHour && startMinute > 0) {
          if (startMinute === 30) {
            availableMinutes = ['30']
          }
        }
        // 如果选择的是结束小时，且结束分钟不是30，则分钟选项需要调整
        else if (selectedHour === endHour && endMinute < 30) {
          if (endMinute === 0) {
            availableMinutes = ['00']
          }
        }

        // 更新分钟选项
        this.pickerRange[1] = availableMinutes

        // 如果当前选中的分钟不在可用范围内，重置为第一个可用选项
        const currentMinute = this.pickerRange[1][this.pickerValue[1]]
        if (!availableMinutes.includes(currentMinute)) {
          this.pickerValue[1] = 0
        }
      }
    }
  }
}
</script>

<style scoped>
.half-hour-picker {
  width: 160rpx;
}

.picker-display {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  background-color: #f8f8f8;
  border-radius: 8rpx;
  border: 1rpx solid #e0e0e0;
  width: 160rpx;
}

.picker-arrow {
  color: #999;
  font-size: 24rpx;
}
</style>
